import Vue from 'vue';
import $api from './interface'
const utils = {
    /**
     * 获取链接指定参数值
     * @param {String} name 参数名
     * @param {String} url 可选 指定链接
     *
     * @return {*} null/''
     */
    getQueryString(name, url) {
        var reg = new RegExp('(?|&)' + name + '=([^&]*)(&|$)', 'i');
        r = url || location;
        var r = (url || location.href).match(reg);

        if (r != null) {
            var value = r[2];
            value = value.replace(/(%22|%3E|%3C|<|>)/g, 'MM');
            if (value == '') {
                //此处为安卓下浏览器的一个坑，匹配正则有区别
                return null;
            } else {
                return decodeURIComponent(value);
            }
        } else {
            return null;
        }
    },
    /**
     * 获取全部链接参数
     * @param {String} url 可选 指定链接
     *
     * @return {Object} vQry
     */
    getQueryObject(url) {
        var sQry = (url || location.search).split('?')[1];
        var vQry = {};
        if (sQry) {
            var arr = sQry.split('&');
            arr.forEach(function(item) {
                var subArr = item.split('=');
                vQry[subArr[0]] = decodeURIComponent(subArr[1] || '');
            });
        }
        return vQry;
    },
    /* toast提示
     * @param {String} tips 提示文字
     *
     * */
    // eslint-disable-next-line no-unused-vars
    alert(tips, times) {
        Vue.prototype.$notification.open({
            message: '信息提示',
            description: tips
        });
        // let optTimes = times || 2500;
        // let $alert = document.getElementById('util-pop-alert');
        // let $style = '';
        // if (!$alert) {
        //     let $body = document.getElementsByTagName('body')[0];
        //     let alertStyle =
        //         '#util-pop-alert{opacity:0;' +
        //         'position: fixed;' +
        //         'pointer-events: none;' +
        //         'z-index: 9999991000;' +
        //         'left: 50%; bottom: 50%;' +
        //         'background-color: rgba(89,89,89,.8);' +
        //         ' color: #fff;' +
        //         'font-size: 16px;' +
        //         'word-break:break-all;' +
        //         'padding: 5px 10px;' +
        //         'border-radius: 5px;' +
        //         'font-family: "Microsoft Yahei",SimHei,"Helvetica Neue","DejaVu Sans",Tahoma;' +
        //         ' pointer-events:none;' +
        //         '-webkit-transform: "translate(-50%,0)"' +
        //         '-webkit-transition: "all .3s ease-in" }';
        //     $style = document.createElement('style');
        //     $alert = document.createElement('div');
        //     $style.innerText = alertStyle;
        //     $alert.id = 'util-pop-alert';
        //     $body.appendChild($alert);
        //     $body.appendChild($style);
        // }
        // $alert = document.getElementById('util-pop-alert');
        // setTimeout(function() {
        //     $alert.innerHTML = tips;
        //     $alert.setAttribute('style', 'opacity:1');
        // });
        // setTimeout(function() {
        //     $alert = document.getElementById('util-pop-alert');
        //     $alert.setAttribute('style', 'opacity:0');
        // }, optTimes);
    },
    mobileConsole(content) {
        var consoleContent = `${this.dateConverter('hh:mm:ss')}: `,
            mobileConsoleStyle =
                '#mobileConsole{position: fixed;pointer-events: none; z-index: 9999991000; right: 0; top: 0; width: 60%; min-height: 20rem;overflow: auto;background-color: rgba(0,0,0,0.6); overflow: auto; color: #fff; font-size: 12px; word-break:break-all; padding: 5px 0; border-radius: 0 0 0 10px; font-family: "Microsoft Yahei",SimHei,"Helvetica Neue","DejaVu Sans",Tahoma; pointer-events:none; } #mobileConsole p{ padding: 4px 10px; margin: 0; border-bottom: 1px rgba(255,255,255,.1) solid;}';

        function isJson(obj) {
            var isjson =
                typeof obj == 'object' &&
                Object.prototype.toString.call(obj).toLowerCase() ==
                    '[object object]' &&
                !obj.length;
            return isjson;
        }
        //创建dom结构和样式
        let $mc = document.getElementById('mobileConsole');
        let $style = '';
        if (!$mc) {
            let $body = document.getElementsByTagName('body')[0];
            $style = document.createElement('style');
            $mc = document.createElement('div');
            $style.innerText = mobileConsoleStyle;
            $mc.id = 'mobileConsole';
            $body.appendChild($mc);
            $body.appendChild($style);
        }
        //如果为json对象，则字符串化
        consoleContent += content;
        if (isJson(content)) {
            consoleContent += JSON.stringify(content);
        }
        //填入数据
        let $p = document.createElement('p');
        $p.innerHTML = consoleContent;
        $mc.insertBefore($p, $mc.childNodes[0]);
    },
    /**
     *var testDate = new Date( 1320336000000 );//这里必须是整数，毫秒
     *var testStr = testDate.format("yyyy年MM月dd日hh小时mm分ss秒");
     *var testStr2 = testDate.format("yyyyMMdd hh:mm:ss");
     */
    dateConverter: function(formatData, timestamp = new Date()) {
        if (this.isNumber(timestamp)) {
            // 数字补充13位数
            let str = timestamp.toString();
            timestamp = Number((str + '0000000000000').slice(0, 13));
            timestamp = Number(timestamp);
        } else if (this.isString(timestamp)) {
            // IOS 需要转成yyyy/MM/dd
            timestamp = timestamp
                .toString()
                .replace(/-/g, '/')
                .replace(/\..$/g, '');
        }

        if (!Date.prototype.format) {
            Date.prototype.format = function(format) {
                var o = {
                    'M+': this.getMonth() + 1, //month
                    'd+': this.getDate(), //day
                    'h+': this.getHours(), //hour
                    'm+': this.getMinutes(), //minute
                    's+': this.getSeconds(), //second
                    'q+': Math.floor((this.getMonth() + 3) / 3), //quarter
                    S: this.getMilliseconds() //millisecond
                };

                if (/(y+)/.test(format)) {
                    format = format.replace(
                        RegExp.$1,
                        (this.getFullYear() + '').substr(4 - RegExp.$1.length)
                    );
                }

                for (var k in o) {
                    if (new RegExp('(' + k + ')').test(format)) {
                        format = format.replace(
                            RegExp.$1,
                            RegExp.$1.length == 1
                                ? o[k]
                                : ('00' + o[k]).substr(('' + o[k]).length)
                        );
                    }
                }
                return format;
            };
        }
        // console.log(timestamp);
        var timeFormat = new Date(timestamp || '');
        return timeFormat.format(formatData);
    },
    isNumber(arg) {
        return typeof arg === 'number' && !isNaN(arg);
    },
    isString(arg) {
        return typeof arg === 'string';
    },
    isObject: function(arg) {
        return typeof arg === 'object' && arg !== null;
    },
    isNull: function(arg) {
        return arg === null;
    },
    isNullOrUndefined: function(arg) {
        return arg == null;
    },
    // 设备类型判断
    getDeviceType() {
        var u = navigator.userAgent;
        var device = 'pc';
        if (u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
            device = 'ios';
        } else if (/Android/i.test(u)) {
            device = 'android';
        }
        return device;
    },
    isIOS() {
        return this.getDeviceType() == 'ios';
    },
    isAndroid() {
        return this.getDeviceType() == 'android';
    },
    getCookie(c_name) {
        if (document.cookie.length > 0) {
            let c_start = document.cookie.indexOf(c_name + '=');
            if (c_start != -1) {
                c_start = c_start + c_name.length + 1;
                let c_end = document.cookie.indexOf(';', c_start);
                if (c_end == -1) c_end = document.cookie.length;
                return unescape(document.cookie.substring(c_start, c_end));
            }
        }
        return '';
    },
    setCookie(c_name, value, day) {
        let exdate = new Date();
        let expiredays = day || 3;
        exdate.setDate(exdate.getDate() + expiredays);
        document.cookie =
            c_name +
            '=' +
            escape(value) +
            (expiredays == null ? '' : ';expires=' + exdate.toGMTString());
    },
    // 判断登录
    authLogin(jumpFlag = true){
        let account = $api.getAccount();
        if(account.phone) {
            return true;
        } else {
            if(jumpFlag) {
                location.replace('/login');
            }
            return false;
        }
    },
    loadJS: function (url, callback) {
        var script = document.createElement('script')
        script.type = 'text/javascript';
        if (script.readyState) {
            script.onreadystatechange = function () {
                if (script.readyState == 'loaded' || script.readyState == 'complete') {
                    script.onreadystatechange = null;
                    if(callback) callback(1);
                }
            };
            script.onerror = function () {
                if(callback) callback(0);
            }
        } else {
            script.onload = function () {
                if(callback) callback(1);
            };
        }
        script.src = url;
        document.getElementsByTagName('head')[0].appendChild(script);
    },
    loadCSS: function (url, callback) {
        var css = document.createElement('link');
        css.rel = 'stylesheet';
        if (css.readyState) {
            css.onreadystatechange = function () {
                if (css.readyState == 'loaded' || css.readyState == 'complete') {
                    css.onreadystatechange = null;
                    if(callback) callback(1);
                }
            };
            css.onerror = function () {
                if(callback) callback(0);
            }
        } else {
            css.onload = function () {
                if(callback) callback(1);
            };
        }
        css.href = url;
        document.getElementsByTagName('head')[0].appendChild(css);
    },
    // 下载附件
    downloadFile(url) {
        window.open(url);
    },
    openDoc(type){
        if(!type) return;
        let list = [
            '',
            'http://www.caixinedu.cn/xieyi/gm.html', // 购买协议
            'http://www.caixinedu.cn/xieyi/ys.html', // 隐私协议
            'http://www.caixinedu.cn/xieyi/fw.html', // 服务协议
        ]
        window.open(list[type])
    }
};

Vue.prototype.$util = utils;
window.$util = utils;
export default utils;
